package com.linyu.linpicturebackend.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linyu.linpicturebackend.common.exception.BusinessException;
import com.linyu.linpicturebackend.common.exception.ErrorCode;
import com.linyu.linpicturebackend.common.utils.ThrowUtils;
import com.linyu.linpicturebackend.constant.UserConstant;
import com.linyu.linpicturebackend.model.dto.user.UserQueryRequest;
import com.linyu.linpicturebackend.model.entity.User;
import com.linyu.linpicturebackend.mapper.UserMapper;
import com.linyu.linpicturebackend.model.enums.UserRoleEnum;
import com.linyu.linpicturebackend.model.vo.LoginUserVO;
import com.linyu.linpicturebackend.model.vo.UserVO;
import com.linyu.linpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
* @author 23087
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-18 17:20:25
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Value("${linyu.password.salt}")
    private String slat;

    /**
     * 用户注册
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param checkPassword 确认密码
     * @return 用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf((userPassword.length() < 8 || checkPassword.length() < 8), ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次密码不一致");
        // 2. 检查用户账号是否和数据库中已有的重复
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserAccount, userAccount);
        Long count = this.baseMapper.selectCount(lambdaQueryWrapper);
        ThrowUtils.throwIf(count>0, ErrorCode.PARAMS_ERROR, "账号已存在，请重新输入");
        // 3. 密码一定要加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据到数据库中
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        return user.getId();
    }

    /**
     * 用户登录
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param request 请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号错误");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "用户密码错误");
        // 2. 对用户传递的密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 3. 查询数据库中的用户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserAccount, userAccount);
        lambdaQueryWrapper.eq(User::getUserPassword, encryptPassword);
        User user = this.baseMapper.selectOne(lambdaQueryWrapper);
        // 不存在，抛异常
        if (user == null){
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 4. 保存用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取加密后的密码
     * @param userPassword 用户密码
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String userPassword){
        // 混淆密码
        return DigestUtils.md5DigestAsHex((userPassword + slat).getBytes());
    }

    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        // 追求性能，可以注释直接返回上述结果
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR);
        return currentUser;
    }

    /**
     * 获取脱敏的用户信息
     * @param user 用户
     * @return 用户脱敏信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取脱敏的用户信息
     * @param user 用户
     * @return 用户脱敏信息
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户信息列表
     * @param userList 用户列表
     * @return 脱敏后的用户信息列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)){
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .toList();
    }

    /**
     * 用户注销
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(userObj == null, ErrorCode.NOT_LOGIN_ERROR, "未登录");
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取查询条件
     * @param userQueryRequest 查询条件
     * @return 条件构造器
     */
    @Override
    public LambdaQueryWrapper<User> getLambdaQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjUtil.isNotNull(id), User::getId, id);
        lambdaQueryWrapper.like(StrUtil.isNotBlank(userName), User::getUserName, userName);
        lambdaQueryWrapper.like(StrUtil.isNotBlank(userAccount), User::getUserAccount, userAccount);
        lambdaQueryWrapper.like(StrUtil.isNotBlank(userProfile), User::getUserProfile, userProfile);
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(userRole), User::getUserRole, userRole);
        // 添加排序条件
        if (StrUtil.isNotBlank(sortField)) {
            if ("ascend".contains(sortOrder)) {
                lambdaQueryWrapper.orderByAsc(getColumnField(sortField));
            } else{
                lambdaQueryWrapper.orderByDesc(getColumnField(sortField));
            }
        }
        return lambdaQueryWrapper;
    }

    /**
     * 获取字段
     * @param sortField 排序字段
     * @return 字段
     */
    private SFunction<User, ?> getColumnField(String sortField) {
        switch (sortField.toLowerCase()) {
            case "id":
                return User::getId;
            case "username":
                return User::getUserName;
            case "useraccount":
                return User::getUserAccount;
            case "userprofile":
                return User::getUserProfile;
            case "userrole":
                return User::getUserRole;
            case "createtime":
                return User::getCreateTime;
            case "updatetime":
                return User::getUpdateTime;
            // 可以根据需要添加更多字段
            default:
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的排序字段");
        }
    }
}




